package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.Constants;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.ContextUtil;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.*;
import com.jsbj.user.mapper.SysEquMapper;
import com.jsbj.user.service.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 设备表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysEquServiceImpl extends ServiceImpl<SysEquMapper, SysEqu> implements ISysEquService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ISysRoleEquService sysRoleEquService;

    @Autowired
    private ISysProjectService sysProjectService;
    @Autowired
    private ISysOrgService sysOrgService;
    @Autowired
    private ISysSystemService sysSystemService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysEquFieldConfigService sysEquFieldConfigService;
    @Autowired
    private ISysGroupService sysGroupService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<SysEqu> getByCondition(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        if (StringUtils.isNotEmpty(tenantCode) && StringUtils.isNotEmpty(userId)) {
            Map<String, Object> paramMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : object.entrySet()) {
                paramMap.put(entry.getKey(), entry.getValue());
            }
            List<SysEqu> list = baseMapper.getByCondition(paramMap);
            if (!CollectionUtils.isEmpty(list)) {
                List<SysDictData> dicDatas = sysDictDataService.getDataByKey("equType");
                for (SysEqu equ : list) {
                    for (SysDictData sysDictData : dicDatas) {
                        if (equ.getEquTypeValue().equals(sysDictData.getDicValue().toString())) {
                            equ.setEquTypeDesc(sysDictData.getDicDesc());
                            continue;
                        }
                    }
                }
            }
            return list;
        }
        return null;
    }

    @Override
    public SysEqu getInfoByEquNum(String equNum) {
        LambdaQueryWrapper<SysEqu> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysEqu::getDisabled, 0);
        wrapper.eq(SysEqu::getEquNum, equNum);
        wrapper.last(" limit 1 ");
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public String add(List<Map<String,Object>> params) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        Integer sucNum = 0;//记录新增成功设备的数
        Integer errNum = 0;//记录新增失败设备的数
        String errMsg ="";
        if(params==null || params.size()<1){
            return null;
        }
        for (Map<String,Object> param:params){
            //将参数转成设备对象
            SysEqu sysEqu = transParam(param);

            //各个子系统维护设备
//            param.put("equId",equId);
            param.put("equNum",sysEqu.getEquNum());
            param.put("longitude",sysEqu.getLongitude());
            param.put("latitude",sysEqu.getLatitude());
            //短信签名
            SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(sysEqu.getTenantCode());
            param.put("smsSignName",sysProject.getSmsTypeDesc());
            param.put("userId",sysEqu.getCreaterId());
            if(StringUtils.isNotEmpty(MapUtils.getString(param,"systemCode"))){
                String systemCode = MapUtils.getString(param,"systemCode");
                {
                    errNum++;
                    errMsg = errMsg+sysEqu.getEquNum()+"服务异常；";
                }
            }
        }
        if(sucNum==0){
            throw new Exception("操作失败");
        }
        if(errNum>0){
            return "操作成功"+sucNum+"台设备，失败"+errNum+"台设备：失败原因"+errMsg;
        }else {
            return "操作成功";
        }

    }

    @Override
    public String update(Map<String, Object> param) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        String id = MapUtils.getString(param,"id");
        if(StringUtils.isEmpty(id)){
            throw new Exception("id不能为空");
        }
        SysEqu equ = baseMapper.selectById(id);
        //将参数转成设备对象
        SysEqu sysEqu = transParam(param);

        //各个子系统维护设备
        param.put("equNum",equ.getEquNum());
        param.put("longitude",sysEqu.getLongitude());
        param.put("latitude",sysEqu.getLatitude());
        //短信签名
        SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(sysEqu.getTenantCode());
        param.put("smsSignName",sysProject.getSmsTypeDesc());
        param.put("userId",sysEqu.getCreaterId());
        if(StringUtils.isNotEmpty(MapUtils.getString(param,"systemCode"))){
            String systemCode = MapUtils.getString(param,"systemCode");

        }
        return "操作成功";
    }

    private SysEqu transParam(Map<String, Object> param) {

        SysEqu sysEqu = JSON.parseObject(JSON.toJSONString(param), SysEqu.class);
        sysEqu.setEquTypeKey("equType");
        //组织 编码特殊处理，字段编码不对应
        if(StringUtils.isNotEmpty(MapUtils.getString(param,"orgCode"))){
            sysEqu.setSecCode(MapUtils.getString(param,"orgCode"));
        }

        //虚拟编号生成规则：实体编号后加 V再加序号,编辑时不需要重新生成equNum
        if(StringUtils.isEmpty(MapUtils.getString(param,"id"))){
            String entityEquNum = MapUtils.getString(param,"entityEquNum");
            String equNum = MapUtils.getString(param,"equNum");
            if(StringUtils.isEmpty(equNum)){
                for (int i=1;i<=10;i++){
                    equNum = entityEquNum + "V" +i;
                    SysEqu equ = getInfoByEquNum(equNum);
                    if(equ==null || StringUtils.isEmpty(equ.getId())){
                        break;
                    }
                }
                sysEqu.setEquNum(equNum);
            }
        }

        //位置数据
        if(StringUtils.isNotEmpty(MapUtils.getString(param,"location"))){
            String location = MapUtils.getString(param,"location");
            String[] locations = location.split(",");
            if(locations!=null && locations.length==2){
                sysEqu.setLongitude(locations[0]);
                sysEqu.setLatitude(locations[1]);
            }
        }
        return sysEqu;
    }

    @Override
    public String delete(String id) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        SysEqu sysEqu = baseMapper.selectById(id);
        return "操作成功";

    }

    @Override
    public List<Map<String,Object>> detail(String id) {
        List<Map<String,Object>> resultList = new ArrayList<>();
        SysEqu sysEqu = baseMapper.selectById(id);
        String tenantCode = sysEqu.getTenantCode();
        String orgCode = sysEqu.getSecCode();
        String systemCode = sysEqu.getSystemCode();
        String equTypeValue = sysEqu.getEquTypeValue();
        SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(tenantCode);
        SysOrg sysOrg = sysOrgService.getInfoByOrgCode(orgCode,tenantCode);
        SysSystem sysSystem = sysSystemService.querySystemBySysCode(systemCode);

        /************公共字段处理开始*************/
        //项目
        Map<String,Object> proMap = new HashMap<>();
        proMap.put("fieldName","项目名称");
        proMap.put("defalutValue",sysProject.getProName());
        proMap.put("unit","");
        //标段
        Map<String,Object> orgMap = new HashMap<>();
        orgMap.put("fieldName","标段名称");
        orgMap.put("defalutValue",sysOrg.getOrgName());
        orgMap.put("unit","");
        //角色
        Map<String,Object> roleMap = new HashMap<>();
        roleMap.put("fieldName","角色名称");
        SysRole sysRole = sysRoleService.queryRoleByEquId(sysEqu.getId());
        roleMap.put("defalutValue",sysRole==null?"":sysRole.getRoleName());
        roleMap.put("unit","");
        //系统
        Map<String,Object> systemMap = new HashMap<>();
        systemMap.put("fieldName","系统名称");
        systemMap.put("defalutValue",sysSystem.getSystemName());
        systemMap.put("unit","");
        //设备类型
        Map<String,Object> equTypeMap = new HashMap<>();
        equTypeMap.put("fieldName","设备类型");
        String sysDictData = sysDictDataService.selectDictDescByKeyAndValue("equType",equTypeValue);
        equTypeMap.put("defalutValue",sysDictData);
        equTypeMap.put("unit","");

        resultList.add(proMap);
        resultList.add(orgMap);
        resultList.add(roleMap);
        resultList.add(systemMap);
        resultList.add(equTypeMap);
        /*****************公共字段处理结束********************/

        //开始处理设备特性字段
        String equType = sysEqu.getEquTypeValue();

        //先查询设备默认字段列表，再加入特殊字段列表
        List<SysEquFieldConfig> configs = sysEquFieldConfigService.queryListBySysCodeAndEquType("0","0","1");
        //特殊配置字段列表
        List<SysEquFieldConfig>  configsT = sysEquFieldConfigService.queryListBySysCodeAndEquType(systemCode,equTypeValue,"1");
        configs.addAll(configsT);
        //设备详细信息
        Map<String,Object> equMap = new HashMap<>();

        //实体设备转成map
        Map<String, Object> equMainMap = JSON.parseObject(JSON.toJSONString(sysEqu), Map.class);
        if(configs!=null && configs.size()>0){
            for (SysEquFieldConfig sysEquFieldConfig:configs){
                Map<String,Object> map = new HashMap<>();
                map.put("fieldName",sysEquFieldConfig.getFieldName());
                map.put("unit",sysEquFieldConfig.getFieldUnit());
                if("location".equals(sysEquFieldConfig.getEquFieldCode())){  //位置特殊处理
                    String location = "";
                    if(MapUtils.getString(equMainMap,"longitude")!=null && MapUtils.getString(equMainMap,"latitude")!=null){
                        location = MapUtils.getString(equMainMap,"longitude")+","+MapUtils.getString(equMainMap,"latitude");
                    }
                    map.put("defalutValue",location);
                }else{
                    //先判断主设备表是否有数据，主设备表没有再去子表查询
                    map.put("defalutValue", MapUtils.getString(equMainMap,sysEquFieldConfig.getEquFieldCode())==null?MapUtils.getString(equMap,sysEquFieldConfig.getEquFieldCode()):MapUtils.getString(equMainMap,sysEquFieldConfig.getEquFieldCode()));
                }
                resultList.add(map);
            }
        }
        return resultList;
    }

    @Override
    public IPage<SysEqu> getList(String inParam) {
        return null;
    }

    @Override
    public List<SysDictData> getEquTypeBySystemCode(String systemCode) {
        return null;
    }

    @Override
    public Map<String,Object> updateDetail(String id) {
        Map<String,Object> resultMap = new HashMap<>();
        SysEqu sysEqu = baseMapper.selectById(id);
        String systemCode = sysEqu.getSystemCode();
        String userId = RequestHeaderUtils.getUserId(request);

        String tenantCode = sysEqu.getTenantCode();
        String orgCode = sysEqu.getSecCode();
        String equTypeValue = sysEqu.getEquTypeValue();
        SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(tenantCode);
        SysOrg sysOrg = sysOrgService.getInfoByOrgCode(orgCode,tenantCode);
        SysSystem sysSystem = sysSystemService.querySystemBySysCode(systemCode);
        SysRole sysRole = sysRoleService.queryRoleByEquId(sysEqu.getId());//角色
        String sysDictData = sysDictDataService.selectDictDescByKeyAndValue("equType",equTypeValue);//设备类型

        sysEqu.setTenantName(sysProject.getProName());
        sysEqu.setSecName(sysOrg.getOrgName());
        sysEqu.setRoleName(sysRole==null?"":sysRole.getRoleName());
        sysEqu.setRoleId(sysRole==null?"":sysRole.getId());
        sysEqu.setSystemName(sysSystem.getSystemName());
        sysEqu.setEquTypeDesc(sysDictData);

        //开始处理设备特性字段
        String equType = sysEqu.getEquTypeValue();

        //试验室特殊处理
        if("14".equals(equType)){
            //试验室
            sysEqu.setTrialRoomCode(sysEqu.getSecCode());
            sysEqu.setTrialRoomName(sysEqu.getSecName());

            //标段
            SysOrg parentOrg = sysOrgService.getInfoByOrgCode(sysOrg.getParentOrgCode(),tenantCode);
            sysEqu.setSecCode(parentOrg.getOrgCode());
            sysEqu.setSecName(parentOrg.getOrgName());
        }

        //试验室特殊处理 end

        //先查询设备默认字段列表，再加入特殊字段列表
        List<SysEquFieldConfig> configs = sysEquFieldConfigService.queryListBySysCodeAndEquType("0","0","1");
        //特殊配置字段列表
        List<SysEquFieldConfig>  configsT = sysEquFieldConfigService.queryListBySysCodeAndEquType(systemCode,equTypeValue,"1");
        configs.addAll(configsT);
//
//
//        List<SysEquFieldConfig> configs = sysEquFieldConfigService.queryListBySysCodeAndEquType(systemCode,equType,"1");
//        //若未查询到数据，则查询默认字段
//        if(configs==null || configs.size()<1){
//            configs = sysEquFieldConfigService.queryListBySysCodeAndEquType("0","0","1");
//        }

        //实体设备转成map
        Map<String, Object> equMainMap = JSON.parseObject(JSON.toJSONString(sysEqu), Map.class);
        if(configs!=null && configs.size()>0){
            for (int i=0;i<configs.size();i++){
                if("location".equals(configs.get(i).getEquFieldCode())){  //位置特殊处理
                    String location = "";
                    if(MapUtils.getString(equMainMap,"longitude")!=null && MapUtils.getString(equMainMap,"latitude")!=null){
                        location = MapUtils.getString(equMainMap,"longitude")+","+MapUtils.getString(equMainMap,"latitude");
                    }
                    configs.get(i).setDefalutValue(location);
                }else{
                    //先判断主设备表是否有数据，主设备表没有再去子表查询
                    configs.get(i).setDefalutValue(MapUtils.getString(equMainMap,configs.get(i).getEquFieldCode())==null?MapUtils.getString(null,configs.get(i).getEquFieldCode()):MapUtils.getString(equMainMap,configs.get(i).getEquFieldCode()));
                }

                //下拉框控件，查询是否需要通过方法调用
                //调用接口的入参
                JSONObject param = new JSONObject();
                param.put("tenantCode",sysEqu.getTenantCode());
                param.put("orgCode",sysEqu.getSecCode());
                param.put("systemCode",systemCode);
                param.put("userId",userId);
                if("select".equals(configs.get(i).getFieldType())){
                    //查询下拉框数据列表是否有值，有值则转成对象
                    List<Map> selectDataList = new ArrayList();
                    if(StringUtils.isNotEmpty(configs.get(i).getSelectDatas())){
                        selectDataList = JSONArray.parseArray(configs.get(i).getSelectDatas(),Map.class);
                    }else if(configs.get(i).getIsFromInterface()==1){ //通过接口查询下拉列表
                        String className = configs.get(i).getInterfaceClassName();
                        String methodName = configs.get(i).getInterfaceMethodName();
//                        selectDataList = ContextUtil.getFromClassMethod(className,methodName,param);
                    }
                    configs.get(i).setSelectDataList(selectDataList);
                }
            }
        }
        resultMap.put("commonField",sysEqu);
        resultMap.put("specialField",configs);
        return resultMap;
    }


}
